﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace ExcelUnity.Core
{
    internal static class CommonHelper
    {
        /// <summary>
        /// 属性是Nullable泛型
        /// </summary>
        /// <param name="property"></param>
        /// <returns></returns>
        public static bool IsNullable(this PropertyInfo property)
        {
            return property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
        }

        public static FileType GetFileType(string path)
        {
            var ext = Path.GetExtension(path).ToLower();
            return ext switch
            {
                ".xlsx" => FileType.Xlsx,
                ".xlx" => FileType.Xls,
                ".csv" => FileType.Csv,
                _ => throw new ArgumentException("不识别的文件类型:" + ext),
            };
        }

        /// <summary>
        /// 值类型转换
        /// </summary>
        /// <param name="value">当前值</param>
        /// <param name="targetType">目标类型</param>
        /// <returns></returns>
        public static object ConvertValueType(string value, Type targetType)
        {
            object ret = targetType.Name switch
            {
                "Guid" => Guid.Parse(value),
                _ => Convert.ChangeType(value, targetType),
            };
            return ret;
        }

        public static bool IsNullOrWhiteSpace(this string? value)
        {
            return string.IsNullOrWhiteSpace(value);
        }

        public static bool IsNotNullOrWhiteSpace(this string? value)
        {
            return !string.IsNullOrWhiteSpace(value);
        }

        public static bool IsNullOrEmpty<T>(this IEnumerable<T>? value)
        {
            return value == null || value.Count() == 0;
        }

        public static bool IsNotNullOrEmpty<T>(this IEnumerable<T>? value)
        {
            return value != null && value.Count() > 0;
        }
    }
}